<template>
  <div class="registerDetail">

    <div class="task_header">
      <div class="top_title">
        <div
          class="top_title_back"
          @click="onClickLeft"
        ><i class="iconfont icon-back"></i></div>
        <div class="top_title_val">
          {{recordId ? '编辑预约单' : '新建预约单' }}
        </div>
      </div>
    </div>
    <!-- 表单 -->
    <div class="formData">
      <van-form ref="form">
        <van-field
          v-model="dataSource.fixCenterName"
          name="维修中心"
          label="维修中心"
          input-align="right"
          placeholder="请选择"
          :rules="[{ required: true }]"
          right-icon="arrow"
          @click="handleSelect('fixCenterId', 'fixCenterName')"
          readonly
        />
        <van-field
          v-model="dataSource.adminOrgName"
          name="品牌"
          label="品牌"
          placeholder="请选择"
          input-align="right"
          :rules="[{ required: true }]"
          right-icon="arrow"
          @click="handleSelect('adminOrgId', 'adminOrgName')"
          readonly
        />

        <van-field
          v-model="dataSource.empName"
          name="预约服务顾问"
          label="预约服务顾问"
          input-align="right"
          placeholder="请选择"
          right-icon="arrow"
          @click="handleSelect('empId', 'empName')"
          readonly
          :rules="[{ required: true }]"
        />

        <van-field
          v-model="dataSource.carNo"
          name="车辆"
          label="车辆"
          input-align="right"
          placeholder="请选择"
          @click="handleSelectCar()"
          right-icon="arrow"
          readonly
        />
        <van-field
          readonly
          clickable
          name="currentDate"
          :value="dataSource.bizDate"
          input-align="right"
          label="预约日期"
          placeholder="请选择时间"
          @click="handleSelectTime('bizDate')"
          :rules="[{ required: true }]"
          right-icon="arrow"
        />
        <van-field
          readonly
          clickable
          name="currentDate"
          :value="dataSource.dateIn"
          input-align="right"
          label="预约进场时间"
          placeholder="请选择时间"
          @click="handleSelectTime('dateIn')"
          right-icon="arrow"
          :rules="[{ required: true }]"
        />
        <van-field
          v-model="dataSource.bookingName"
          name="预约类型"
          label="预约类型"
          input-align="right"
          placeholder="请选择"
          right-icon="arrow"
          @click="handleSelect('bookingType', 'bookingName')"
          readonly
          :rules="[{ required: true }]"
        />
        <van-field
          v-if="dataSource.bookingType == 3"
          v-model="dataSource.taskTypeName"
          name="招揽类型"
          label="招揽类型"
          input-align="right"
          placeholder="请选择"
          right-icon="arrow"
          @click="handleSelect('taskTypeId', 'taskTypeName')"
          readonly
          :rules="[{ required: true }]"
        />
        <!-- <van-field
          v-model="dataSource.workBillName"
          name="工单类型"
          label="工单类型"
          input-align="right"
          placeholder="请选择"
          right-icon="arrow"
          @click="handleSelect('workBillType', 'workBillName')"
          readonly
          :rules="[{ required: true }]"
        /> -->
        <!-- <van-field
          v-model="dataSource.repairpricetypeName"
          name="维修价格类型"
          label="维修价格类型"
          input-align="right"
          placeholder="请选择"
          right-icon="arrow"
          @click="handleSelect('repairpricetypeId', 'repairpricetypeName')"
          readonly
          :rules="[{ required: true }]"
        />
        <van-field
          v-model="dataSource.materialPriceName"
          name="配件价格类型"
          label="配件价格类型"
          input-align="right"
          placeholder="请选择"
          right-icon="arrow"
          @click="handleSelect('materialPriceId', 'materialPriceName')"
          readonly
          :rules="[{ required: true }]"
        /> -->

        <van-field v-model="dataSource.remark" name="备注" label="备注" type="textarea" input-align="left" placeholder="" autosize />

        <!-- 时间选择弹窗 -->

        <van-popup v-model="showTimerPicker" position="bottom">
          <van-datetime-picker
            type="datetime"
            v-model="currentDate"
            @confirm="onTimeConfirm($event)"
            @cancel="showTimerPicker = false"
            :formatter="formatter"
          />
        </van-popup>

        <!-- 下拉选择弹窗 -->
        <van-popup v-model="showSelectPicker" position="bottom">
          <van-field
            name="模糊查询"
            v-if="likeWhoField == 'fixCenterId' || likeWhoField == 'empId'"
            input-align="left"
            v-model="likeWho"
            label="模糊查询"
            placeholder="请输入模糊查询关键词"
          />
          <van-picker show-toolbar :columns="columns" @confirm="handleSelectConfirm" @cancel="showSelectPicker = false" value-key="name" />
        </van-popup>

        <!-- 多选弹窗 -->
        <div class="submitBtn" @click="formOnSubmit">确认</div>
      </van-form>
      <MultipleSelect :visible="showMultipleVisible" @close="showMultipleVisible = false" @multipleSubmit="multipleSubmit"></MultipleSelect>
    </div>
    <!-- 车辆选择 -->
    <!-- <van-popup class="carPop" v-model="carVisible" position="right"> -->
    <CarList @close="carVisible = false" @getCarData="getCarData" :fixCenterId="''" :visible="carVisible"></CarList>
    <!-- </van-popup> -->
  </div>
</template>

<script>
import { DatetimePicker, Empty, Field, Form, Notify, Popup, Search, Toast, Uploader } from 'vant'
import MultipleSelect from '../../components/MultipleSelect/index.vue'
import repairApi from '@/api/repairApi'
import commonApi from '@/api/commonApi'
import { getCookies, getFilterData } from '@/utils/util.js'
import store from '@/store'
import carApi from '@/api/carApi'
import CarList from '../car/index'

export default {
  name: 'applyRepairEdit',
  components: {
    Search,
    Empty,
    Field,
    Form,
    Uploader,
    DatetimePicker,
    MultipleSelect,
    Popup,
    CarList,
    Toast,
  },
  data() {
    return {
      showTimerPicker: false,
      dataSource: {
        adminOrgId: '', //品牌id，String，必填
        adminOrgName: '', //品牌id，String，必填
        fixCenterId: '', //维修中心ID值,
        fixCenterName: '',
        carInfoId: '',
        carModelId: '', //车型，ID值,必填，String
        carModelName: '', //车型，ID值,必填，String
        empId: '', //服务顾问id,必填，String
        empName: '',
        // materialPriceId: "", //配件价格类型id,必填，String
        // materialPriceName: "",
        // repairpricetypeId: "", //维修价格类型id,必填，String
        // repairpricetypeName: "",
        bizDate: '', //预约时间
        dateIn: '', //预约进场时间
        bookingType: '', //预约类型,
        bookingName: '',
        // workBillType: "",
        // workBillName: "",
        remark: '',
        carNo: '',
        taskTypeId: '',
        taskTypeName: '',
      },
      uploader: [],
      columns: [],
      showSelectPicker: false,
      disabled: false,
      editType: '',
      field: '',
      fieldName: '',
      showMultipleVisible: false,
      empList: [],
      userId: getCookies('userId'),
      brandList: [],
      fixCenterList: [],
      bookingTypeList: [],
      workBillTypeList: [],
      repairpricetypeList: [],
      materialPriceList: [],
      currentDate: new Date(),
      taskId: '',
      carId: '',
      carVisible: false,
      likeWhoField: '',
      likeWho: '',
      taskTypeList: [],
      recordId: '',
    }
  },
  watch: {
    // dataSource: {
    //   handler(val) {
    //     store.commit('setAddCarInfo', val)
    //     console.log(val)
    //   },
    //   deep: true,
    // },
    'dataSource.fixCenterId': {
      handler(val, OldVal) {
        if (val) {
          this.getBrandByFixCenter()
          this.getEmpPerson()
          // this.getMaterialPriceType();
          if (val != OldVal && OldVal) {
            // this.dataSource.carInfoId = "";
            // this.dataSource.vinCode = "";
            // this.dataSource.carNo = "";
            // Notify({
            //   type: "warning",
            //   message: "切换维修中心请重新录入车辆信息",
            // });
          }
        }
      },
      deep: true,
    },
    likeWho: function (nval, oval) {
      if (this.likeWhoField == 'fixCenterId') {
        if (nval) {
          let newArr = this.fixCenterList.filter((item) => {
            return item.name.indexOf(nval) > -1
          })
          this.columns = newArr
        } else {
          this.columns = this.fixCenterList
        }
      }
      if (this.likeWhoField == 'empId') {
        if (nval) {
          let newArr = this.empList.filter((item) => {
            return item.name.indexOf(nval) > -1
          })
          this.columns = newArr
        } else {
          this.columns = this.empList
        }
      }

      // v-if="likeWhoField == 'fixCenterId'||likeWhoField=='carModelId'"
    },
  },

  mounted() {
    this.getMainFixCenter()
    this.getBookingTypeList()
    // this.getWorkBillTypeList();
    // this.getRepairpricetype();
    if (this.$route.query && this.$route.query.billId) {
      this.getDetail(this.$route.query.billId)
      this.recordId = this.$route.query.billId
      document.title = '编辑预约单'
    }
    if (this.$route.query && this.$route.query.taskId) {
      this.taskId = this.$route.query.taskId
    }
    if (this.$route.query && this.$route.query.carId) {
      this.carId = this.$route.query.carId
      this.getCarInfoBase(this.carId)
    }
  },
  destroyed() {
    if (this.$route.path != '/applyRepairEdit' && this.$route.path != '/car') {
      localStorage.removeItem('carData')
      store.commit('setAddCarInfo', {})
    }
  },
  methods: {
    getDetail(billId) {
      repairApi
        .queryRepairBookingById({
          billId,
          userId: this.userId,
        })
        .then((res) => {
          if (res.data) {
            this.dataSource = JSON.parse(JSON.stringify(res.data))
            this.dataSource.bookingType = this.dataSource.bookingTypeValue
            this.dataSource.bookingName = this.formatList(this.bookingTypeList, 'value', this.dataSource.bookingType)
            this.dataSource.workBillType = this.dataSource.workBillTypeValue
            this.dataSource.workBillName = this.formatList(this.workBillTypeList, 'value', this.dataSource.workBillType)
            this.dataSource.repairpricetypeId = this.dataSource.repairPriceId
            this.dataSource.repairpricetypeName = this.dataSource.repairPrice
            this.dataSource.adminOrgId = this.dataSource.brandId
            this.dataSource.adminOrgName = this.dataSource.brandName
            this.dataSource.carInfoId = this.dataSource.carId
            this.dataSource.materialPriceId = this.dataSource.mterialPriceTypeId
            this.dataSource.materialPriceName = this.dataSource.mterialPriceType
            this.dataSource.remark = this.dataSource.remark
            this.getBrandByFixCenter()
            this.getTaskType()
          }
        })
    },
    getCarData(data) {
      let carData = JSON.parse(JSON.stringify(data))
      this.dataSource.carInfoId = carData.billId
      this.dataSource.vinCode = carData.vinCode
      this.dataSource.carNo = carData.carNo
    },
    // 获取维修中心
    getMainFixCenter() {
      commonApi
        .getMainFixCenter({
          fixCenterId: '',
          userId: this.userId,
          type: 'fixCenter',
        })
        .then((res) => {
          if (res.data) {
            this.fixCenterList = res.data
            // if (
            //   store.state.addCarInfoStore.addCarInfo &&
            //   JSON.stringify(store.state.addCarInfoStore.addCarInfo) != '{}'
            // ) {
            //   this.dataSource = store.state.addCarInfoStore.addCarInfo
            //   console.log(this.dataSource)
            //   if (localStorage.getItem('carData')) {
            //     let carData = JSON.parse(localStorage.getItem('carData'))
            //     this.dataSource.carInfoId = carData.billId
            //     this.dataSource.vinCode = carData.vinCode
            //     this.dataSource.carNo = carData.carNo
            //   }
            //   this.filterFixCenterData()
            // } else {
            //   if (localStorage.getItem('carData')) {
            //     let carData = JSON.parse(localStorage.getItem('carData'))
            //     this.dataSource.carInfoId = carData.billId
            //     this.dataSource.vinCode = carData.vinCode
            //     this.dataSource.carNo = carData.carNo
            //   }
            // }
          }
        })
    },
    //如果从其他入口进入，则去获取对应的车辆详情
    getCarInfoBase(id) {
      carApi.getCarInfoBase({ id }).then((res) => {
        if (res.code == 1) {
          console.log('---', res.data)
          this.dataSource.fixCenterId = res.data.fixCenterId
          this.dataSource.fixCenterName = res.data.fixCenterName
          this.dataSource.carInfoId = res.data.id
          this.dataSource.carModelName = res.data.carModelNameName
          this.dataSource.carModelId = res.data.carModelNameId
          this.dataSource.empId = res.data.serverPsnId
          this.dataSource.empName = res.data.serverPsnName
          this.dataSource.carNo = res.data.carNo
          this.getBrandByFixCenter()
        }
      })
    },
    // 获取品牌
    getBrandByFixCenter() {
      commonApi
        .getBrandByFixCenter({
          fixCenterId: this.dataSource.fixCenterId,
          userId: this.userId,
        })
        .then((res) => {
          if (res.data) {
            this.brandList = res.data
          }
        })
    },
    // 获取服务人员
    getEmpPerson() {
      commonApi
        .getEmpPerson({
          fixCenterId: this.dataSource.fixCenterId,
          userId: this.userId,
          type: 'taskFollow',
        })
        .then((res) => {
          if (res.data) {
            this.empList = res.data
          }
        })
    },
    // 获取预约类型

    getBookingTypeList() {
      commonApi
        .getEnums({
          key: 'bookingType',
          userId: this.userId,
        })
        .then((res) => {
          if (res.data) {
            this.bookingTypeList = res.data
          }
        })
    },

    // 获取任务类型
    getTaskType() {
      commonApi.getTaskType({}).then((res) => {
        this.taskTypeList = res.data
      })
    },
    // 获取工单类型

    // getWorkBillTypeList() {
    //   commonApi
    //     .getEnums({
    //       key: "workBillTypeNewRep",
    //       userId: this.userId,
    //     })
    //     .then((res) => {
    //       if (res.data) {
    //         this.workBillTypeList = res.data;
    //       }
    //     });
    // },

    // 获取维修价格
    // getRepairpricetype() {
    //   commonApi.getRepairpricetype({}).then((res) => {
    //     if (res.data) {
    //       this.repairpricetypeList = res.data;
    //       res.data.forEach((item) => {
    //         if (item.name == "标准单价") {
    //           this.dataSource.repairpricetypeId = item.billId;
    //         }
    //       });
    //     }
    //   });
    // },
    // 获取配件价格
    // getMaterialPriceType() {
    //   commonApi
    //     .getMaterialPriceType({ fixCenterId: this.dataSource.fixCenterId })
    //     .then((res) => {
    //       if (res.data) {
    //         this.materialPriceList = res.data;
    //         res.data.forEach((item) => {
    //           if (item.name == "标准价格") {
    //             this.dataSource.materialPriceId = item.billId;
    //           }
    //         });
    //       }
    //     });
    // },
    formatList(data, key, value) {
      if (data && data.length != 0) {
        let obj = data.filter((item) => item[key] == value)
        if (obj.length != 0) {
          return obj[0].name
        }
      }
      return null
    },
    // 重新通过维修中心筛选出对应的数据
    filterFixCenterData() {
      let fixCenterData = getFilterData(this.fixCenterList, 'billId', this.dataSource.fixCenterId)
      this.field = 'fixCenterId'
      this.fieldName = 'fixCenterName'
      this.handleSelectConfirm(fixCenterData)
    },
    // 选择下拉
    handleSelect(field, fieldName) {
      if (field == 'fixCenterId') {
        this.columns = this.fixCenterList
      } else if (field == 'adminOrgId') {
        if (!this.dataSource.fixCenterId) {
          Toast('请先选择维修中心')
          return
        }
        this.columns = this.brandList
      } else if (field == 'empId') {
        if (!this.dataSource.fixCenterId) {
          Toast('请先选择维修中心')
          return
        }
        this.columns = this.empList
      } else if (field == 'bookingType') {
        this.columns = this.bookingTypeList
      } else if (field == 'workBillType') {
        this.columns = this.workBillTypeList
      } else if (field == 'repairpricetypeId') {
        this.columns = this.repairpricetypeList
      } else if (field == 'materialPriceId') {
        this.columns = this.materialPriceList
      } else if (field == 'taskTypeId') {
        this.columns = this.taskTypeList
      }

      this.showSelectPicker = true

      this.field = field
      this.fieldName = fieldName
      this.likeWhoField = field
    },
    // 选择下拉确认
    handleSelectConfirm(value) {
      console.log(value)
      if (this.field == 'workBillType' || this.field == 'bookingType') {
        this.dataSource[this.field] = value ? value.value : ''
        this.dataSource[this.fieldName] = value ? value.name : ''
        if (value.value == 3) {
          this.getTaskType()
        }
      } else {
        this.dataSource[this.field] = value ? value.billId : ''
        this.dataSource[this.fieldName] = value ? value.name : ''
      }
      if (this.field == 'fixCenterId') {
        this.getBrandByFixCenter()
        this.clearBrand()
        this.fixCenterList.forEach((item) => {
          console.log(item.billId)
          console.log(value.billId)
          if (item.billId == value.billId) {
            this.dataSource.adminOrgId = item.brandId
            this.dataSource.adminOrgName = item.brandName
            this.dataSource.showOrgId = item.showOrgId
            this.dataSource.showOrgName = item.showOrgName
          }
        })
      }

      this.likeWho = ''

      this.showSelectPicker = false
    },
    clearBrand() {
      this.dataSource.adminOrgId = ''
      this.dataSource.adminOrgName = ''
      this.dataSource.showOrgId = ''
      this.dataSource.showOrgName = ''
    },

    onTimeConfirm(val) {
      let year = val.getFullYear()
      let month = val.getMonth() + 1
      let day = val.getDate()
      let hour = val.getHours()
      let minute = val.getMinutes()
      // let second = val.getSeconds()
      if (month >= 1 && month <= 9) {
        month = `0${month}`
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`
      }
      if (hour >= 0 && hour <= 9) {
        hour = `0${hour}`
      }
      if (minute >= 0 && minute <= 9) {
        minute = `0${minute}`
      }
      // if (second >= 0 && second <= 9) { second = `0${second}` }
      this.dataSource[this.timeField] = `${year}-${month}-${day} ${hour}:${minute}:00`
      this.showTimerPicker = false
    },

    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`
      } else if (type === 'month') {
        return `${value}月`
      } else if (type === 'day') {
        return `${value}日`
      } else if (type === 'hour') {
        return `${value}时`
      } else if (type === 'minute') {
        return `${value}分`
      } else if (type === 'second') {
        return `${value}秒`
      }
      return value
    },
    // 时间选择
    handleSelectTime(field) {
      this.timeField = field
      this.showTimerPicker = true
    },
    handleMoreSelect() {
      this.showMultipleVisible = true
    },
    // 多选确认
    multipleSubmit(data) {
      if (data && data.length != 0) {
        this.dataSource.empName = data.map((item) => item.name).join(',')
        this.dataSource.empId = data.map((item) => item.value).join(',')
      }
    },
    handleSelectCar() {
      // this.$router.push('/car')
      this.carVisible = true
    },
    formOnSubmit() {
      this.$refs.form
        .validate()
        .then(() => {
          if (!this.dataSource.billId) {
            repairApi
              .addRepairBooking({
                ...this.dataSource,
                taskId: this.taskId,
                userId: this.userId,
              })
              .then((res) => {
                console.log(res)
                if (res.code != 0) {
                  Notify({ type: 'success', message: '提交成功' })
                  this.$router.go(-1)
                }
              })
          } else {
            repairApi
              .updateRepaitBooking({
                ...this.dataSource,
                taskId: this.taskId,
                userId: this.userId,
              })
              .then((res) => {
                console.log(res)
                if (res.code != 0) {
                  Notify({ type: 'success', message: '提交成功' })
                  this.$router.go(-1)
                }
              })
          }
        })
        .catch(() => {
          this.$toast.fail('请完善信息')
        })
    },
    onClickLeft() {
      this.$router.go(-1)
    },
  },
}
</script>

<style lang="less" scoped>
.flex {
  display: flex;
  align-items: center;
}
.registerDetail {
  background: #f3f3f3;
  overflow: auto;
  .detail_header {
    justify-content: space-between;
    margin: 0.2rem 0.2rem;
    border-radius: 5px;
    background: #fff;
    padding: 0.3rem;
    .detail_header_lt {
      .carNo {
        font-size: 0.32rem;
        font-weight: bold;
        margin-bottom: 0.2rem;
        .icon-right {
          margin-left: 0.2rem;
          color: #409eff;
        }
      }
      .hank {
        font-size: 0.28rem;
        color: #666;
      }
    }
    .detail_header_rt {
      justify-content: flex-start;
      .txt {
        font-size: 0.28rem;
        color: #161616;
      }
      .icon-tel {
        color: #fff;
        background: #35bc04;
        font-size: 0.32rem;
        padding: 0.1rem;
        border-radius: 50%;
        margin-right: 0.1rem;
      }
    }
  }
  .formData {
    background: #fff;
    padding-bottom: 25px;
    margin-top: 50px;
  }
}
/deep/.van-field__error-message {
  text-align: right;
}
.submitBtn {
  background: #409eff;
    background: linear-gradient(316deg, #3975c6 0%, #71a4ea 100%);
    color: #fff;
  width: 75%;
  margin: auto;
  text-align: center;
  padding: 0.25rem;
  border-radius: 5px;
  margin-top: 0.6rem;
  font-size: 0.3rem;
}
.carPop {
  width: 100%;
  height: 100%;
}
.task_header {
  background: url('~@/assets/images/title_bg.png') no-repeat center;
  font-size: 0.24rem;
  height: 50px;
  background-size: 100% 100%;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 9;

  .top_title {
    position: relative;
    width: 100%;
    height: 50px;

    .top_title_back {
      position: absolute;
      left: 10px;
      line-height: 50px;
      color: #fff;
    }

    .top_title_val {
      text-align: center;
      line-height: 50px;
      color: #fff;
      font-weight: bold;
      font-size: 16px;
    }
    .task_transbox {
      position: absolute;
      right: 10px;
      top: 5px;
      color: #fff;
      z-index: 10;
      font-weight: 400;
      font-size: 10px;
      text-align: center;
      .task_trans {
        width: 24px;
        display: block;
        margin: auto;
      }
    }
  }

  .task_header_data {
    .task_header_date {
      margin-bottom: 10px;
      display: flex;
      align-items: center;

      .task_header_date_w {
        width: 12.5%;
      }

      .task_header_date_item {
        width: 12.5%;
        text-align: center;
        color: #fff;
        font-size: 14px;
      }
    }

    .task_header_followData {
      display: flex;
      align-items: center;
      color: #fff;
      margin-bottom: 10px;

      .task_header_followData_tt {
        width: 12.5%;
        text-align: center;
      }

      .task_header_followData_item {
        width: 12.5%;
        text-align: center;
        font-size: 12px;
        font-weight: bold;
      }
    }
  }
}
</style>
